package com.zjw.service.message;

import com.zjw.service.message.impl.MemoryMessageDataBase;

import java.util.List;

public class MessageTransferService {

    private final IMessageDataBase messageDataBase = new MemoryMessageDataBase();

    private final IUserPool userPool;

    public MessageTransferService(IUserPool userPool) {
        this.userPool = userPool;
    }

    void transferTo(Message message) {
        long toId = message.getToId();

        IConnectSession connectSession = userPool.getConnectSession(toId);

        if (connectSession == null) {
            messageDataBase.insertMessageList(message);
        } else {
            connectSession.writeMessage(message);
        }
    }


    void requestMessageList(long userId) {
        List<Message> messages = messageDataBase.removeMessageList(userId);
        if (messages != null) {
            IConnectSession connectSession = userPool.getConnectSession(userId);
            messages.forEach(connectSession::writeMessage);
        }
    }

    public IUserPool getUserPool() {
        return userPool;
    }
}
